//
//  GCDViewController.swift
//  Swift 3.0 基础语法
//
//  Created by YYY on 2017/7/18.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class GCDViewController: CommonViewController {

    override func viewDidLoad()
    {
        super.viewDidLoad()

        
        
        
        //尾随闭包 
        //如果函数的最后一个参数是闭包，函数参数可以提前结束，最后一个参数直接使用{}包装闭包的代码
        loadData { (completion) in
            
            print(completion)
            
        }

        //'weak' must be a mutable variable, because it may change at runtime
        //weak 只能修饰var
        // ! 强行解包,如果self已经被销毁，强行解包会导致崩溃
        //强行解包需要参与计算
        
        // ? 可选解包，如果self已经被销毁，不会向对象发送getter消息，更加安全
        //？不能直接参与计算
        weak var weakSelf = self
        loadData { _ in
            print(weakSelf?.view)
            
            print(weakSelf?.view)
        }

   
//        loadData { [unowned self] in
//            
//        }
        // Do any additional setup after loading the view.
    }
    //增加一个闭包参数
    
    func loadData(completion: @escaping ([String]) -> ())
    {
        //将任务添加到队列，指定执行任务的函数
        //队列调度任务，以同步、异步方式执行
        

        //全局队列
        DispatchQueue.global().async {
            print("全局队列:耗时操作：\(Thread.current)")
        }
        //停留
        Thread.sleep(forTimeInterval: 3)
        let json = ["芒果","土豆","爱奇艺"]
        
        //主队列
        DispatchQueue.main.async {
            print("主队列:主线程刷新UI \(Thread.current)")
            completion(json)
        }
        
        //异步执行任务，获取结果，通过block／闭包回调
        //闭包的应用场景和block完全一致
    }
    
    func demo1() -> ()
    {
        //尾随闭包
        DispatchQueue.global().async { 
            
            DispatchQueue.main.async(execute: { 
                
            })
        }
        //尾随闭包
        DispatchQueue.main.async { 
            
        }
    }

    //1:在对象销毁前，自动调用
    //2:没有（）不让重载
    //3:没有func 不让调用
    //MARK: - 析构函数 KVO NSTimer  CADisplayLink
    deinit {
        print("销毁了")
    }
    //OC必须释放的对象：通知、KVO、NSTimer、CADisplayLink
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
